/********************************************************
 * Filename: NewTclPackage.java
 * Author: LMU
 * Program: TUnit
 * Description: Creates a new tcl package.  
 * Revision History:
 * 20060517: Initial Revision.
 * *****************************************************/

package edu.lmu.cs.tUnit.wizard;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;

import edu.lmu.cs.tUnit.log.TUnitLog;
import edu.lmu.cs.tUnit.plugin.TUnitPlugin;

/**
 * Class to create a new tcl package
 * @author LMU  
 */
public class NewTclPackage extends Wizard implements INewWizard {

	private NewTclPackagePage page;
	private ISelection selection;

	/**
	 * Constructor for NewTclPackage.
	 */
	public NewTclPackage() {
		super();
		setWindowTitle("New Tcl Package");
		setNeedsProgressMonitor(true);
	}
	
	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		page = new NewTclPackagePage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final String containerName = page.getContainerName();
		final String fileName = page.getPackageName();
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(containerName, fileName, monitor);
				} catch (IOException e) {
					TUnitLog.logError("Could not create new Tcl Package " + page.getPackageName() + ".", e);
				} catch (CoreException e) {
					TUnitLog.logError("Could not create new Tcl Package " + page.getPackageName() + ".", e);
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will find the container, create the
	 * file if missing or just replace its contents, and open
	 * the editor on the newly created file.
	 */
	private void doFinish(String containerName, String packageName, IProgressMonitor monitor)
		throws CoreException, IOException {
		// create a sample file
		monitor.beginTask("Creating " + packageName, 2);
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = root.findMember(new Path(containerName));
		if (!resource.exists() || !(resource instanceof IContainer)) {
			throwCoreException("Project \"" + containerName + "\" does not exist.");
		}
		IContainer container = (IContainer) resource;
		IFolder folder = container.getFolder(new Path(packageName));
		try {
			if (folder.exists()) {
				// do nothing
			} else {
				// Create new package file
				monitor.worked(1);
				folder.create(true, true, monitor);
				String filePath = container.getLocation().toString();
				IFile newFile = container.getFile(new Path(packageName + "/" + packageName + ".tcl"));
				newFile.create(null, true, monitor);
				
				File file = new File(filePath + "/" +  packageName + "/" + packageName + ".tcl");
				copyFile(file);
				processSampleFile(file, packageName);
				
				// Update init.tcl
				File initFile = new File(filePath + "/init.tcl");
				updateInitFile(initFile, packageName, filePath);
			}
		} catch (IOException e) {
			TUnitLog.logError("Could not create new Tcl Package " + page.getPackageName() + ".", e);
		}
		monitor.worked(2);
		TUnitLog.logInfo("New Tcl Package " + packageName + " created.");
	}

	private void throwCoreException(String message) throws CoreException {
		IStatus status =
			new Status(IStatus.ERROR, "test", IStatus.OK, message, null);
		throw new CoreException(status);
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
	
	/**
	 * Copy template file to output file
	 * @param templateFile
	 * @param fileOut
	 * @throws IOException
	 */
	private static void copyFile(File outputFile) throws IOException {
		URL SAMPLE = TUnitPlugin.getDefault().getBundle().getEntry("/resource/samplePackage.tcl");
		InputStream in = SAMPLE.openStream();
		OutputStream out = new FileOutputStream(outputFile);
	    
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
	
	/**
	 * Make changes to the template file.
	 * @throws IOException 
	 */
	private void processSampleFile(File file, String name) throws IOException {
		String fileBuffer = openFile(file);
		
		Pattern p = Pattern.compile("samplePackage");
		Matcher m = p.matcher(fileBuffer);
		fileBuffer = m.replaceAll(name);
			
		writeFile(fileBuffer, file);
	}
	
	/**
     * Opens a file and imports it.
	 * @throws IOException 
	 * @throws FileNotFoundException 
     */
	private String openFile(File file) throws FileNotFoundException, IOException {	
		StringBuffer buffer = new StringBuffer();
		
		BufferedReader in = new BufferedReader(
				new FileReader(file.getCanonicalPath()));
		String line;
		while ((line = in.readLine()) != null) {
			buffer.append(line).append("\n");
		}
		in.close();
		return buffer.toString();
	}
	
	/**
     * Creates a new output file and saves the changes to it.
	 * @throws IOException 
     */
	private void writeFile(String fileBuffer, File ouputFile) throws IOException {
		BufferedWriter out = new BufferedWriter(new FileWriter(ouputFile));
		out.write(fileBuffer);
		out.close();
	}
	
	/**
     * Updates init.tcl
	 * @throws IOException 
     */
	private void updateInitFile(File file, String packageName, String filePath) throws IOException {
		FileInputStream init = new FileInputStream(file);
		File outFile = new File(filePath + "init.tmp");
		BufferedReader in = new BufferedReader(new InputStreamReader(init));
		FileOutputStream out = new FileOutputStream(outFile);
		PrintWriter pOut = new PrintWriter(out);
		String thisLine = "";
		
		while((thisLine = in.readLine()) != null) {
			pOut.println(thisLine);
		}
		
		pOut.println("package require " + packageName);
		pOut.flush();
		pOut.close();
		in.close();
		
		file.delete();
		outFile.renameTo(file);
	}
}
